﻿using Microsoft.Extensions.Hosting;
using System;
using System.Reflection;
using Topshelf;

namespace H2O.Assistant
{
    public class Program
    {      
        /// <summary>
        /// 主方法
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {            
            NLog.ILogger logger = NLog.LogManager.GetCurrentClassLogger();
            AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();

            // 配置服务宿主
            var rc = HostFactory.Run(x =>
            {
                // 配置服务类型
                x.Service<IHost>(s =>
                {
                    // 构造服务实例
                    s.ConstructUsing(() => Host.CreateDefaultBuilder(args: args).Build());

                    // 当服务启动后, 执行点什么
                    s.WhenStarted(tc =>
                    {
                        tc.StartAsync();
                    });

                    // 当服务停止后, 执行点什么
                    s.WhenStopped(tc =>
                    {
                        tc.StopAsync();
                    });
                });

                // 服务用本地系统账号运行
                x.RunAsLocalSystem();

                // 服务描述信息
                x.SetDescription($"{assemblyName.Name} Description");

                // 服务显示名称
                x.SetDisplayName($"{assemblyName.Name} DisplayName");

                // 服务名称
                x.SetServiceName($"{assemblyName.Name}");
                x.EnableServiceRecovery(config =>
                {
                    config.RestartService(delayInMinutes: 5);
                    config.RestartService(delayInMinutes: 15);
                    config.RestartService(delayInMinutes: 30);
                    config.OnCrashOnly();
                    config.SetResetPeriod(days: 1);
                });
                x.UseNLog();                
                x.OnException((exception) =>
                {
                    logger.Error(exception, "Topshelf.OnException()");
                });
            });

            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
            Environment.ExitCode = exitCode;
        }
    }
}
